from django.urls import path

from . import views

UPDATE_STOCKS_ON_STARTUP = False

app_name='zylinder_app'
urlpatterns = [
    path('', views.main, name='main'),
    path('newPlayer', views.newPlayer, name='newPlayer'),
    path('resetPlayer', views.resetPlayer, name='resetPlayer'),
    path('youLost', views.youLost, name='youLost'),
    path('hasLost', views.hasLost, name='hasLost'),
    path('tradeHistory', views.TradeHistoryView.as_view(), name='tradeHistory'),
    path('getMoney', views.getMoney, name='getMoney'),
    path('getCurrentStocks', views.getCurrentStocks, name='getCurrentStocks'),
    path('getAvailableStocks', views.getAvailableStocks, name='getAvailableStocks'),
    path('getStocks', views.getStocks, name='getStocks'),
    path('buyStocks', views.buyStocks, name='buyStocks'),
    path('sellStocks', views.sellStocks, name='sellStocks'),

]

## do one-time at start
# fill stock db
from .models import Stock
from .backend import stock_controller as StockScraper
from django.db.utils import OperationalError
def updateStocks():
    def fillDB(dict_stocks: dict):
        print(f"There are {len(dict_stocks)} stocks in the provided list.")
        for df_stock in dict_stocks:
            newStock = Stock()
            newStock.symbol = df_stock["symbol"]
            newStock.description = df_stock["description"]
            newStock.save()
        print(f"There are currently {Stock.objects.all().count()} Stocks in the DB. Old Stocks will not be deleted.")

    print("Updating stock symbols, this will take some time...")
    fillDB(StockScraper.getAllUsStocks())
    print("Finished updating stocks.")


try:
    if UPDATE_STOCKS_ON_STARTUP or not Stock.objects.all():
        updateStocks()
except OperationalError:
    # if the "Stock" table hasnt been created, don't update it. 
    print("The \"Stock\" table doesn't exist. Did you already apply migrations?")
    pass
